import hashlib
import random
import string


def random_salt(length=16):
    """
    生成一个给定长度的随机字符串
    :param length:
    :return:
    """
    return "".join(
        random.choice(string.ascii_letters + string.digits) for _ in range(length)
    )


def sha256_hash(text):
    """
    对文件内容进行sha256加密
    :param text:
    :return:
    """
    sha256 = hashlib.sha256()
    salt = random_salt()
    text = text + salt
    sha256.update(text.encode("utf-8"))
    return sha256.hexdigest() + "$" + salt


def sha256_verify(text, hashed_text):
    """
    验证文本内容的sha256加密是否正确
    :param text:
    :param hashed_text:
    :return:
    """
    try:
        hash_value, salt = hashed_text.split("$")
        if hash_value == hashlib.sha256((text + salt).encode("utf-8")).hexdigest():
            return True
        else:
            return False
    except:
        return False


if __name__ == "__main__":
    print(sha256_hash("admin"))
    print(
        sha256_verify(
            "4ec2d72b27d2a949a5c8c25ce0035d5c58694d4d0aa608a81f460414b98d48ca$FxetsNAtFLdkMFyv",
            "admin",
        )
    )
